/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.huagege.view;

import java.awt.event.KeyEvent;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import com.huagege.bean.Transfer;
import com.huagege.bean.User;
import com.huagege.exception.TransferException;
import com.huagege.service.TransferService;
import com.huagege.service.TransferServiceImpl;

/**
 * 账户记录主界面
 * 功能：存款，取款，转账，刷新（未实现，没必要）
 * @author wubobo
 *
 */
public class MainView extends javax.swing.JFrame {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private User user;
    /**
     * Creates new form MainView
     * @throws TransferException 
     */
    public MainView(User user) throws TransferException {
    	this.user = user;
        initComponents(transferService.transferData(user));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     * @param data 
     * @param data 
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents(Object[][] data) {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("账户记录");
        setResizable(false);
        
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });
        jTextField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        jLabel1.setText("金额：");

        jButton1.setText("存钱");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("取钱");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("转账");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        tableModel = new DefaultTableModel(data,new String []{"账户","金额","来源","时间","余额"}) {
            Class[] types = new Class [] {
                    java.lang.String.class, java.lang.Double.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class
                };
                boolean[] canEdit = new boolean [] {
                    false, false, false, false, false
                };

                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            };
        jTable1.setModel(tableModel);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setResizable(false);
            jTable1.getColumnModel().getColumn(1).setResizable(false);
            jTable1.getColumnModel().getColumn(2).setResizable(false);
            jTable1.getColumnModel().getColumn(3).setResizable(false);
            jTable1.getColumnModel().getColumn(3).setPreferredWidth(200);
            jTable1.getColumnModel().getColumn(4).setResizable(false);
        }

        jButton4.setText("刷新");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                .addGap(6, 6, 6))
        );

        jTextField1.getAccessibleContext().setAccessibleDescription("目标账号");

        pack();
    }
    
	/**
	 * 存钱按钮监听
	 * @param evt
	 */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    	try {
    	double money =Double.parseDouble(jTextField1.getText());
    	Transfer drawTransfer = null;
    	transferService = new TransferServiceImpl(user);
		drawTransfer = transferService.deposit(user.getUsername(), money);
		tableModel.addRow(drawTransfer.toDataArray());
		jTextField1.setText("");
		} catch (TransferException e) {
			JOptionPane.showMessageDialog(null, "交易失败");
		}catch(NumberFormatException e){
			JOptionPane.showMessageDialog(null, "输入有误");
		}
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * 取钱按钮监听
     * @param evt
     */
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    	try {
    	double money =Double.parseDouble(jTextField1.getText());
    	Transfer drawTransfer = null;
    	transferService = new TransferServiceImpl(user);
		drawTransfer = transferService.draw(user.getUsername(), money);
		tableModel.addRow(drawTransfer.toDataArray());
		jTextField1.setText("");
		} catch (TransferException e) {
			JOptionPane.showMessageDialog(null, "交易失败");
		}catch(NumberFormatException e){
			JOptionPane.showMessageDialog(null, "输入有误");
		}
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * 刷新按钮监听
     * @param evt
     */
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    	
    }

    /**
     * 转账按钮监听
     * @param evt
     */
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    	try {
    		if(jTextField2.getText().equals(""))
    			throw new TransferException("对方账号为空");
    		if(user.getUsername().equals(jTextField2.getText()))
    			throw new TransferException("不能向自己转账");
    	double money =Double.parseDouble(jTextField1.getText());
    	String target = jTextField2.getText();
    	Transfer drawTransfer = null;
    	transferService = new TransferServiceImpl(user);
		drawTransfer = transferService.transfer(user.getUsername(), target, money);
		tableModel.addRow(drawTransfer.toDataArray());
		jTextField1.setText("");
		jTextField2.setText("");
		} catch (TransferException |ArrayIndexOutOfBoundsException e) {
			JOptionPane.showMessageDialog(null, "交易失败");
		}catch(NumberFormatException e){
			JOptionPane.showMessageDialog(null, "请正确输入");
		}
    }

    /**
     * 文本框，表格键盘监听
     * 按esc退出登录
     * @param evt
     */
    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
    	if(evt.getKeyCode()==KeyEvent.VK_ESCAPE){
    		new LoginView().setVisible(true);
    		this.dispose();
    	}
    }//GEN-LAST:event_formKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }


    private TransferService transferService = new TransferServiceImpl(user);
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private DefaultTableModel tableModel;
}
